20
var fs = require("fs");
var request = require("request");
var Bagpipe = require("bagpipe");
var Axios = require("axios");
var bagpipe = new Bagpipe(300);

function fetchPage(x) {
  startRequest(x);
}

async function downloadFile(imgUrl, filepath) {
  const writer = fs.createWriteStream(filepath); // 创建写入对象
  const response = await Axios({
    url: imgUrl,
    method: "GET",
    responseType: "stream",
  }); // 请求图片地址获取二进制数据流
  response.data.pipe(writer); // 写入图片数据到文件中
  return new Promise((resolve, reject) => {
    writer.on("finish", resolve);
    writer.on("error", reject);
  });
}

let startIndexZ = 12;
let endIndexZ = 20;

function startRequest() {
  for (let z = startIndexZ; z < endIndexZ; z++) {
    !fs.existsSync(`D:/mapbox-tiles/${z}`) &&
      fs.mkdirSync(`D:/mapbox-tiles/${z}`);

    // let startIndexX = (z == 0 || z == 1) ? 0 : 3 * Math.pow(2, z - 2);

    // let endIndexX = (z == 0 || z == 1) ? Math.pow(2, z) : Math.pow(2, z);

    // let startIndexY = (z == 0 || z == 1) ? 0 : Math.pow(2, z - 2);

    // let endIndexY = (z == 0 || z == 1) ? Math.pow(2, z) : Math.pow(2, z - 1);

    let startIndexX = Math.pow(2, z - 10) * 855;
    let endIndexX = Math.pow(2, z - 10) * 859;
    let startIndexY = Math.pow(2, z - 10) * 389;
    let endIndexY = Math.pow(2, z - 10) * 393;

    for (let x = startIndexX; x < endIndexX; x++) {
      !fs.existsSync(`D:/mapbox-tiles/${z}/${x}`) &&
        fs.mkdirSync(`D:/mapbox-tiles/${z}/${x}`);

      for (let y = startIndexY; y < endIndexY; y++) {
        const url = `http://api.mapbox.com/styles/v1/moe0321/ckr0etlqn0frq18qct6uuvy3v/tiles/512/${z}/${x}/${y}@2x?access_token=pk.eyJ1IjoibW9lMDMyMSIsImEiOiJja3E3bGJnZzMwN2E5MnZ1aGJueGhxcG4xIn0.Q5KTu5uyl2FtILHUMDQ1xA`;

        const name = `${y}.png`;
        const dest = `D:/mapbox-tiles/${z}/${x}/` + name;
        !fs.existsSync(dest) && bagpipe.push(downloadFile, url, dest);
      }
    }
  }
}

fetchPage(); //主程序开始运行
